<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      class="form-search"
    >
      <SearchTool
        :code="{
          factory: 'factoryAffiliation',
        }"
        v-model:factory="queryParams.factory"
        :showWorkshop="false"
        :showLine="false"
        :showSection="false"
      ></SearchTool>

      <el-form-item label="产品编号" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option
            v-for="dict in tech_process_manage_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
        <el-button icon="refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="plus"
          @click="handleAdd"
          v-hasPermi="['technology:processManage:add']"
        >
          新增
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="edit"
          :disabled="single"
          @click="handleDetail"
          v-hasPermi="['technology:processManage:edit']"
          >编辑</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['technology:processManage:remove']"
        >
          删除
        </el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="processManageList"
      border
      @selection-change="handleSelectionChange"
      show-overflow-tooltip
    >
      <el-table-column type="selection" width="55" :selectable="selectable" align="center" />
      <el-table-column label="工艺编号" prop="processCode">
        <template #default="scope">
          <el-link type="primary" @click="handleDetail(scope.row)">
            {{ scope.row.processCode }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="产品编号" align="center" prop="productCode" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品分类" align="center" prop="productSort" />
      <el-table-column label="工厂" align="center" prop="factoryAffiliation" />
      <el-table-column label="标准生产数量" align="center" prop="prodAmount" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="规格" align="center" prop="standards" />
      <el-table-column label="型号" align="center" prop="model" />
      <el-table-column label="版本" align="center" prop="version" />
      <el-table-column label="最后更新时间" align="center" prop="updateTime" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="tech_process_manage_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="left"
        fixed="right"
        min-width="200"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            v-if="scope.row.status === '0'"
            link
            type="primary"
            icon="edit"
            @click="handleUpdate(scope.row, '1')"
            v-hasPermi="['technology:processManage:edit']"
          >
            试用
          </el-button>
          <el-button
            v-if="scope.row.status === '0'"
            link
            type="primary"
            icon="delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['technology:processManage:remove']"
          >
            删除
          </el-button>
          <el-button
            v-if="scope.row.status !== '0'"
            link
            type="primary"
            icon="edit"
            @click="handleUpgrade(scope.row)"
            v-hasPermi="['technology:processManage:upgrade']"
          >
            升级版本
          </el-button>
          <el-button
            v-if="scope.row.status === '1' || scope.row.status === '3'"
            link
            type="primary"
            icon="edit"
            @click="handleUpdate(scope.row, '2')"
            v-hasPermi="['technology:processManage:edit']"
          >
            启用
          </el-button>
          <el-button
            v-if="scope.row.status === '1' || scope.row.status === '2'"
            link
            type="primary"
            icon="edit"
            @click="handleUpdate(scope.row, '3')"
            v-hasPermi="['technology:processManage:edit']"
          >
            停用
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工艺管理对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="700px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-button type="primary" @click="handleSelectPro" style="margin-bottom: 10px">
        选择产品
      </el-button>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品编号" prop="productCode">
              <!-- <el-input
                v-model="form.productCode"
                readonly
                placeholder="请选择产品"
              > -->
              {{ form.productCode }}
              <!-- <template #append>
                  <el-button icon="Promotion" @click="handleSelectPro" />
                </template> -->
              <!-- </el-input> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              {{ form.productName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品分类" prop="productSort">
              {{ form.productSort }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工厂" prop="factoryAffiliation">
              {{ form.factoryAffiliation }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标准生产数量" prop="prodAmount">
              {{ form.prodAmount }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              {{ form.unit }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="standards">
              {{ form.standards }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              {{ form.model }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本" prop="version">
              <el-input v-model="form.version" placeholder="请输入版本" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <proDialog v-model:show="showModal" @change="selectPro"></proDialog>
    <el-dialog
      :close-on-click-modal="false"
      v-model="dialogFormVisible"
      title="升级版本"
      width="500px"
    >
      <el-form :model="upgradeForm" :rules="rules">
        <el-form-item label="新版本" prop="version">
          <el-input v-model="upgradeForm.version" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmUpgrade">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProcessManage">
import {
  listProcessManage,
  addProcessManage,
  updateProcessManage,
  delProcessManage,
  upgradeSubProcessManage,
} from "@/api/technology/processManage";
import { deepClone } from "@/utils";
import proDialog from "./proDialog";
import { useRouter } from "vue-router";
import { ref, reactive, toRefs, getCurrentInstance } from "vue";
const router = useRouter();
const open = ref(false);
const showModal = ref(false);
const dialogFormVisible = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const formRef = ref("formRef");
// 工艺管理表格数据
const processManageList = ref([]);
const data = reactive({
  form: {},
  upgradeForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productCode: null,
    productName: null,
    factoryAffiliation: null,
    factory: null,
  },
  rules: {
    version: [{ required: true, message: "版本不能为空", trigger: "blur" }],
  },
});
const selectable = (row) => row.status == "0";
const { queryParams, form, rules, upgradeForm } = toRefs(data);
const { proxy } = getCurrentInstance();
const { tech_process_manage_status } = proxy.useDict("tech_process_manage_status");
/** 查询工艺管理列表 */
function getList() {
  loading.value = true;
  listProcessManage(queryParams.value).then((response) => {
    processManageList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function handleSelectPro() {
  showModal.value = true;
}
function selectPro(val) {
  form.value.productCode = val.prodNo;
  form.value.productName = val.prodName;
  form.value.productSort = val.prodTypeName;
  form.value.factoryAffiliation = val.factoryName;
  form.value.factory = val.factoryCode;

  form.value.prodAmount = val.standardProdCount;
  form.value.unit = val.unit;
  form.value.standards = val.packages;
  form.value.model = val.model;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    productCode: null,
    productName: null,
    productSort: null,
    factoryAffiliation: null,
    prodAmount: null,
    unit: null,
    standards: null,
    model: null,
    version: null,
    factory: null,
    status: "0",
  };
  proxy.resetForm("form");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  queryParams.value.factory = null;
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}
function handleDetail(row) {
  const id = row.id || ids.value;
  router.push("/processManage/detail/" + id);
  // proxy.subPage(DetailPage, { title: "物料内部调拨详情", data: row }, () => {
  //   this.getList();
  // });
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增工艺";
  form.value.version = "v1.0";
}
/** 修改按钮操作 */
function handleUpdate(row, status) {
  const operationList = {
    1: "试用",
    2: "启用",
    3: "停用",
  };
  const operation = operationList[status];
  proxy.$modal
    .confirm(`确定${operation}${row.productName}${row.version}吗？`)
    .then(function () {
      const params = deepClone(row);
      params.status = status;
      return updateProcessManage(params).then(() => {
        proxy.$modal.msgSuccess(`${operation}成功`);
        getList();
      });
    })
    .then(() => {
      getList();
    })
    .catch(() => {});
}
function confirmUpgrade() {
  upgradeSubProcessManage(upgradeForm.value).then(() => {
    dialogFormVisible.value = false;
    getList();
  });
}

/** 修改按钮操作 */
function handleUpgrade(row) {
  listProcessManage({
    pageNum: 1,
    pageSize: 10000,
    productCode: row.productCode,
  }).then((response) => {
    let latestVersion = "v1.0";
    if (response.rows && response.rows.length) {
      latestVersion = response.rows[response.rows.length - 1].version || "v1.0";
    }

    const index = latestVersion.indexOf(".");
    const pre = latestVersion.substring(0, index + 1);
    const currentNum = latestVersion.substring(index + 1, index + 2);
    dialogFormVisible.value = true;
    upgradeForm.value.version =
      pre + (Number(currentNum) || currentNum == 0 ? Number(currentNum) + 1 : 0);
    upgradeForm.value.processManageId = row.id;
  });
}
/** 提交按钮 */
function submitForm() {
  if (!form.value.productCode) {
    proxy.$modal.msgError("请选择产品");
    return;
  }
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateProcessManage(form.value).then(() => {
          proxy.$modal.msgSuccess("编辑成功");
          open.value = false;
          getList();
        });
      } else {
        addProcessManage(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  let msg = "";
  if (row.processCode) {
    msg = `是否确认删除工艺编号为"${row.processCode}"数据项？`;
  } else {
    msg = `是否确认删除所选数据项？`;
  }
  proxy.$modal
    .confirm(msg)
    .then(function () {
      return delProcessManage(id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
getList();
</script>
